package com.zsk.mqtt.device;

import java.net.URISyntaxException;
import java.util.Scanner;

import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.MqttTopic;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;

import java.util.Scanner;
import java.util.concurrent.ScheduledExecutorService;

public class Push {

	public static final String SERVER_URL = "tcp://127.0.0.1:61613";
	public static final String TOPIC = "/niiam/do/cmd";
	public static final String clientid = "client4";

	public static MqttClient client;
	private MqttConnectOptions options;
	private String userName = "admin";
	private String passWord = "password";

	private ScheduledExecutorService scheduler;

	private void start() throws Exception {
		client = new MqttClient(SERVER_URL, clientid, new MemoryPersistence());
		options = new MqttConnectOptions();
		options.setCleanSession(true);
		options.setUserName(userName);
		options.setPassword(passWord.toCharArray());
		options.setConnectionTimeout(20);
		options.setKeepAliveInterval(20);
		client.setCallback(new PushCallback());
		MqttTopic topic = client.getTopic(TOPIC);
		client.connect(options);
		int[] Qos = { 2 };
		String[] topic1 = { TOPIC };
		client.subscribe(topic1, Qos);
	}

	public void stop() {
		try {
			client.disconnect();
			System.out.println("断开连接 ......");
		} catch (MqttException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public static void main(String[] args) throws Exception {
		Push client = new Push();
		client.start();
		System.out.println("订阅中......"+client.TOPIC);
		Scanner scan = new Scanner(System.in);
		String in = "";
		while (true) {
			System.out.println("请输入内容：\n");
			in = scan.nextLine();
			Push.client.publish("/zhangsike/client/push/msg", new MqttMessage(in.getBytes()));
			
		}
	}
}
